package com.zcf.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zcf.common.json.Body;
import com.zcf.mapper.NoticeMapper;
import com.zcf.pojo.Dining;
import com.zcf.pojo.Notice;
import com.zcf.pojo.User;
import com.zcf.service.NoticeService;
import com.zcf.utils.Hutool;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhouzhuang
 * @since 2018-11-28
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {
	@Autowired
	private NoticeMapper noticeMapper;

	public Body setNotice(String userId, String content, String title, String files, String din_id) {
		Notice notice = new Notice();

		User user = new User();
		if (userId == null) {
			//return Body.newInstance("用户不存在");
		}else{

			user.setId(userId);
			user = user.selectById();
		}
		if (din_id!= null) {
			Dining dining = new Dining();
			dining.setId(din_id);
			dining = dining.selectById();
			if (dining != null) {
				notice.setDinName(dining.getDiningName());
			}

			Notice notice2 = new Notice();
			EntityWrapper<Notice> ewq = new EntityWrapper<>();
			ewq.eq("din_id", din_id);
			List<Notice> list = notice2.selectList(ewq);
			if (list.size() > 0) {
				for (Notice notice3 : list) {
					notice2.setId(notice3.getId());
					notice2.deleteById();
				}
			}
		}
		notice.setContent(content);
		notice.setId(Hutool.getId());
		notice.setUserId(userId);
		notice.setTitle(title);
		notice.setImage(files);
		if(userId!=null) {
			if (user.getPhone() != null && !user.getPhone().equals("")) {
				notice.setPhone(user.getPhone());
			}
			if (user.getName() != null && !user.getName().equals("")) {
				notice.setUserName(user.getName());
			}
		}

		notice.setTime(Hutool.parseDateToString());
		if (din_id != null) {
			notice.setDin_id(din_id);
		}
		Integer insert = noticeMapper.insert(notice);
		if (insert > 0) {
			return Body.newInstance(notice);
		}
		return Body.newInstance(501, "插入公告失败");
	}

	@Override
	public Body updateNotice(String id, String userId, String content, String title, String file, String din_id) {
		Notice notice = new Notice();
		notice.setContent(content);
		notice.setId(id);
		if (userId != null) {
			notice.setUserId(userId);
		}
		notice.setTitle(title);
		notice.setImage(file);
		notice.setTime(Hutool.parseDateToString());
		if (din_id != null) {
			notice.setDin_id(din_id);
		}
		Boolean flag = notice.updateById();
		if (flag) {
			return Body.newInstance(notice);
		}
		return Body.newInstance(-1, "修改公告失败");
	}

}
